package ${groupId}.service.system.sysrole;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ${groupId}.dal.mybatis.mapper.SysRoleMapper;
import ${groupId}.dal.mybatis.mapper.SysRoleResourceMapper;
import ${groupId}.dal.mybatis.mymapper.MySysRoleResourceMapper;
import ${groupId}.dal.mybatis.model.SysRole;
import ${groupId}.dal.mybatis.model.SysRoleExample;
import ${groupId}.dal.mybatis.model.SysRoleExample.Criteria;
import ${groupId}.service.system.sysrole.dto.SysRoleAddItemReqDto;
import ${groupId}.service.system.sysrole.dto.SysRoleQueryFilter;
import ${groupId}.service.system.sysrole.dto.SysRoleUpdateItemReqDto;
import ${groupId}.dal.mybatis.model.SysRoleResource;
import ${groupId}.dal.mybatis.model.SysRoleResourceExample;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.system.core.results.ResultBase;
import com.system.core.view.layui.table.TableViewRspDto;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SysRoleService {
	
	private SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Autowired
	private SysRoleMapper sysRoleMapper;
	@Autowired
	private SysRoleResourceMapper sysRoleResourceMapper;
	@Autowired
	private MySysRoleResourceMapper mySysRoleResourceMapper;
	
	public String genRoleCode() {
		SimpleDateFormat roleDate = new SimpleDateFormat("yyyyMMddHHmmss");
		return "role_"+roleDate.format(new Date());
	}
	
	public Map<String,Collection<String>> roleResourceList(Long roleId) {
		Map<String,Collection<String>> map = new HashMap<String, Collection<String>>();
		mySysRoleResourceMapper.roleResourceList(roleId).forEach(roleResource->{
			
			if(map.containsKey(roleResource.getRoleCode())) {
				map.get(roleResource.getRoleCode()).add(roleResource.getPermission());
			} else {
				Collection<String> list = new ArrayList<>();
				list.add(roleResource.getPermission());
				map.put(roleResource.getRoleCode(), list);
			}
			
		});
		return map;
	}
	
	@Transactional
	public ResultBase updateRoleResource(List<SysRoleResource> sysRoleResources) {
		ResultBase result = new ResultBase();
		
		SysRoleResourceExample example = new SysRoleResourceExample();
		example.createCriteria().andRoleIdEqualTo(sysRoleResources.get(0).getRoleId());
		sysRoleResourceMapper.deleteByExample(example);
		
		sysRoleResources.forEach(sysRoleResource -> {
			sysRoleResourceMapper.insertSelective(sysRoleResource);
		});
		result.setSuccess(true);
		result.setMessage("更新成功");
		return result;
	}
	
	public List<Long> getResrouceByRoleId(Long roleId){
		SysRoleResourceExample example = new SysRoleResourceExample();
		example.createCriteria().andRoleIdEqualTo(roleId);
		List<SysRoleResource> list = sysRoleResourceMapper.selectByExample(example);
		List<Long> resourceIds = new ArrayList<Long>();
		list.forEach(roleResource -> {
			resourceIds.add(roleResource.getResourceId());
		});
		return resourceIds;
	}
	
	public List<SysRole> sysRoleListAll(){
		return sysRoleMapper.selectByExample(null);
	}
	
	/**
	 * 页面列表查询
	 * @return TableViewRspDto 返回TableViewRspDto视图对象，符合Layui规范
	 */
	public TableViewRspDto<SysRole> sysRoleList(SysRoleQueryFilter filter){
		log.debug("[sysRole]查询入参：{}",filter);
		TableViewRspDto<SysRole> pageResult = new TableViewRspDto<SysRole>();
		SysRoleExample example = new SysRoleExample();
		Criteria criteria = example.createCriteria();
		//在此插入查询条件start
		if(filter.getId() != null) {
			criteria.andIdEqualTo(filter.getId());
		}
		if(StringUtils.isNotBlank(filter.getRoleName())) {
			criteria.andRoleNameEqualTo(filter.getRoleName());
		}
		if(StringUtils.isNotBlank(filter.getRoleCode())) {
			criteria.andRoleCodeEqualTo(filter.getRoleCode());
		}
		/**
		 * jdbcType:timestamp
		 */
		try {
			if(StringUtils.isNotBlank(filter.getCreateTimeStrStart())) {
				criteria.andCreateTimeGreaterThanOrEqualTo(timeformat.parse(filter.getCreateTimeStrStart()));
			}
			if(StringUtils.isNotBlank(filter.getCreateTimeStrEnd())) {
				criteria.andCreateTimeLessThanOrEqualTo(timeformat.parse(filter.getCreateTimeStrEnd()));
			}
		} catch (ParseException e) {
			e.printStackTrace();
			pageResult.setMessage(e.getMessage());
			return pageResult;
		}
		/**
		 * jdbcType:timestamp
		 */
		try {
			if(StringUtils.isNotBlank(filter.getUpdateTimeStrStart())) {
				criteria.andUpdateTimeGreaterThanOrEqualTo(timeformat.parse(filter.getUpdateTimeStrStart()));
			}
			if(StringUtils.isNotBlank(filter.getUpdateTimeStrEnd())) {
				criteria.andUpdateTimeLessThanOrEqualTo(timeformat.parse(filter.getUpdateTimeStrEnd()));
			}
		} catch (ParseException e) {
			e.printStackTrace();
			pageResult.setMessage(e.getMessage());
			return pageResult;
		}
		//在此插入查询条件end
		
		Page<SysRole> page = PageHelper.startPage(filter.getPage(), filter.getLimit());
		example.setOrderByClause("create_time desc");
		pageResult.setData(sysRoleMapper.selectByExample(example));
		pageResult.setCount(page.getTotal());
		pageResult.setCode(0);
		pageResult.setMessage("查询成功");
		return pageResult;
	}
	
	/**
	 * 根据主键获取单条数据
	 * @param sysRole 使用sysRole对象的主键属性Id类型是Long
	 */
	public SysRole sysRoleGetByPrimaryKey(SysRole sysRole) {
		SysRole result = sysRoleMapper.selectByPrimaryKey(sysRole.getId());
		return result;
	}
	
	/**
	 * 根据主键更新数据
	 * @param sysRole 被更新对象（请注意，只更新有值属性）
	 */
	public ResultBase sysRoleUpdateByPrimaryKey(SysRoleUpdateItemReqDto sysRoleUpdateItemReqDto) {
		ResultBase resultBase = new ResultBase();
		SysRole sysRole = new SysRole();
		BeanUtils.copyProperties(sysRoleUpdateItemReqDto, sysRole);
		sysRoleMapper.updateByPrimaryKeySelective(sysRole);
		resultBase.setSuccess(true);
		resultBase.setMessage("更新成功");
		return resultBase;
	}
	
	/**
	 * 根据主键删除数据
	 * @param keys 被删除对象主键List集合
	 */
	@Transactional
	public ResultBase sysRoleDeleteByPrimaryKey(List<Long> keys) {
		ResultBase resultBase = new ResultBase();
		for(Long id:keys) {
			SysRole sysRole = sysRoleMapper.selectByPrimaryKey(id);
			if(StringUtils.isNotBlank(sysRole.getRoleCode())
					&& sysRole.getRoleCode().toLowerCase().startsWith("system")) {
				resultBase.setMessage("角色"+sysRole.getRoleName()+"不能删除，因为角色代码为：["+sysRole.getRoleCode()+"]");
				return resultBase;
			}
		}
		try {
			keys.forEach((key)->{
				sysRoleMapper.deleteByPrimaryKey(key);
			});
		} catch (Exception e) {
			resultBase.setMessage(e.getMessage());
			return resultBase;
		}
		resultBase.setSuccess(true);
		resultBase.setMessage("成功删除"+keys.size()+"条记录");
		return resultBase;
	}
	
	/**
	 * 新增数据
	 * @param sysRoleAddItemReqDto 新增对象
	 */
	@Transactional
	public ResultBase sysRoleSave(SysRoleAddItemReqDto sysRoleAddItemReqDto) {
		ResultBase resultBase = new ResultBase();
		SysRole sysRole = new SysRole();
		BeanUtils.copyProperties(sysRoleAddItemReqDto, sysRole);
		sysRoleMapper.insertSelective(sysRole);
		resultBase.setSuccess(true);
		resultBase.setMessage("新增成功");
		return resultBase;
	}
}
